package com.yuehuanghun.framework.util;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;

public class DatabaseUtil {
	private DatabaseUtil() {		
	}
	
	public static DataBase getDataBase(DataSource dataSource) {
		String url = getUrl(dataSource);
		DataBase[] values = DataBase.values();
		for (DataBase database : values) {
            if (url.contains(":" + database.getDbName() + ":")) {
                return database;
            }
        }
		return DataBase.UNKNOWN;
	}
	
	
	private static String getUrl(DataSource dataSource) {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            return conn.getMetaData().getURL();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(conn);
        }
    }
	
	private static void closeConnection(Connection conn) {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public enum DataBase {
	    MYSQL("mysql"), 
	    ORACLE("oracle"), 
	    POSTGRESQL("postgresql"), 
	    SQLSERVER("sqlserver"), 
	    DAMENG("dm"),
	    UNKNOWN("");
	    
	    private String dbName;
	    
	    private DataBase(String dbName) {
	        this.dbName = dbName;
	    }
	    
	    public String getDbName() {
	        return this.dbName;
	    }
	    
	    public boolean isOracle() {
	        return this.equals(ORACLE);
	    }
	    
	    public boolean isSqlserver() {
	        return this.equals(SQLSERVER);
	    }
	    
	    public boolean isPostgresql() {
	    	return this.equals(POSTGRESQL);
	    }
	}
}
